//
//  RegisterView.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/2/6.
//

import Foundation
import UIKit

class RegisterView: UIView {

    let userTF = BSTextField(withModal: userM)
    let phoneTF = BSTextField(withModal: phoneM)
    let codeTF = BSTextField(withModal: codeM)
    let imgCodeTF = BSTextField(withModal: imgCodeM)
    let netTF = BSTextField(withModal: netM)
    let postTF = BSTextField(withModal: postM)
    let pswTF = BSTextField(withModal: pswM)
    let againPswTF = BSTextField(withModal: aPswM)
    let confrimBtn = UIButton.createPrimaryLarge("确认注册")

    var postDatas: [SelectPopModal] = []

    var uuid: String? = ""
    var smsCaptchaEnabled: Bool = false
    var retryCount = -1

    var netModal: DeptTreeModal?
    var postModal: SelectPopModal?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(textFiledEditChanged), name: UITextField.textDidChangeNotification, object: userTF.titleTF)
        NotificationCenter.default.addObserver(self, selector: #selector(textFiledEditChanged), name: UITextField.textDidChangeNotification, object: pswTF.titleTF)
        NotificationCenter.default.addObserver(self, selector: #selector(textFiledEditChanged), name: UITextField.textDidChangeNotification, object: phoneTF.titleTF)
        NotificationCenter.default.addObserver(self, selector: #selector(textFiledEditChanged), name: UITextField.textDidChangeNotification, object: againPswTF.titleTF)
        
        reloadData()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var registerM: RegisterParam {
        var modal = RegisterParam()
        modal.username = phoneTF.titleTF.text
        modal.password = pswTF.titleTF.text
        modal.nickname = userTF.titleTF.text
        modal.deptId = String(netModal?.id ?? -1)
        modal.postId = postModal?.id
        if uuid != nil {
            modal.uuid = uuid
        }
        if smsCaptchaEnabled == true {
            modal.code = codeTF.titleTF.text
        } else {
            modal.code = imgCodeTF.titleTF.text
        }
       return modal
    }
    
    func reloadData() {
        imgCodeTapped()

        API.commonSetting { responseModel in
            if responseModel.errorCode == .Success {
                self.smsCaptchaEnabled = responseModel.model?.smsCaptchaEnabled ?? false
                DispatchQueue.main.async {
                    self.codeTF.isHidden = self.smsCaptchaEnabled == false

                    if self.smsCaptchaEnabled == false {
                        self.codeTF.snp.remakeConstraints { (make) -> Void in
                            make.top.equalTo(self.imgCodeTF.snp.bottom)
                            make.height.equalTo(0)
                        }
                    }
                }
            }
        }
        
        API.getRPostlist { responseModel in
            self.postDatas.removeAll()
            let models = responseModel.models ?? []
            models.forEach { m in
                self.postDatas.append(SelectPopModal(id: String(m?.postId ?? -1), name: String(m?.postName ?? "")))
            }
        }
    }
    
    @objc func textFiledEditChanged() {
        let isEnabled = userTF.isEnable && pswTF.isEnable && phoneTF.isEnable && againPswTF.isEnable
        confrimBtn.isEnabled = isEnabled
    }
    
    @objc func imgCodeTapped() {
        API.getCaptchaImage { responseModel in
            if responseModel.errorCode == .Success {
                self.retryCount = -1
                self.uuid = responseModel.model?.uuid
                let img = UIImage.base64ToImage(responseModel.model?.img)
                DispatchQueue.main.async {
                    self.imgCodeTF.imgBtn.setImage(img, for: .normal)
                }
            } else {
                if self.retryCount < 5 {
                    self.imgCodeTapped()
                    self.retryCount += 1
                }
            }
        }
    }
    
    @objc func netTapped() {
        getFirstViewController()?.popup.bottomSheet(bgColor: .black.withAlphaComponent(0.65)) {
            let v = CornerView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: ScreenHeight * 0.9))
            v.corners = SBRectCorner(topLeft: 12, topRight: 12, bottomLeft: 0, bottomRight: 0)
            v.backgroundColor = .white
            
            let rPopV = RDeptTreePopView()
            rPopV.delegate = self
            v.addSubview(rPopV)
            rPopV.snp.makeConstraints { (make) -> Void in
                make.top.right.left.bottom.equalToSuperview()
            }
            return v
        }
    }
    
    @objc func postTapped() {
        getFirstViewController()?.popup.bottomSheet(bgColor: .black.withAlphaComponent(0.65)) {
            let v = CornerView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 386))
            v.corners = SBRectCorner(topLeft: 12, topRight: 12, bottomLeft: 0, bottomRight: 0)
            v.backgroundColor = .white
            let rPopV = SelectPopView()
            rPopV.datas = postDatas
            rPopV.didSelectItemWith = { (index, modal) -> () in
                self.getFirstViewController()?.popup.dismissPopup()
                self.postModal = modal
                self.postTF.titleTF.text = modal.name
            }
            v.addSubview(rPopV)
            rPopV.snp.makeConstraints { (make) -> Void in
                make.top.right.left.bottom.equalToSuperview()
            }
            return v
        }
    }
    
    func setupUI() {
        let scrollV = UIScrollView()
        scrollV.showsVerticalScrollIndicator = false
        scrollV.alwaysBounceVertical = true
        addSubview(scrollV)
        scrollV.snp.makeConstraints { (make) -> Void in
            make.top.left.bottom.equalToSuperview()
            make.right.equalTo(self.snp.right)
            make.width.equalTo(ScreenWidth)
        }
        
        let titleL = UILabel()
        titleL.font = UIFont.systemFont(ofSize: 22)
        titleL.textColor = .black
        titleL.text = "注册"
        scrollV.addSubview(titleL)
        titleL.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(scrollV.snp.top).offset(5)
            make.left.equalTo(scrollV.snp.left).offset(40)
        }
        
        let desL = UILabel()
        desL.font = UIFont.systemFont(ofSize: 17)
        desL.textColor = .pmGray
        desL.text = "请完善个人信息"
        desL.textAlignment = .center
        scrollV.addSubview(desL)
        desL.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(titleL.snp.bottom).offset(11)
            make.left.equalTo(scrollV.snp.left).offset(40)
        }
    
        scrollV.addSubview(userTF)
        userTF.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(desL.snp.bottom).offset(52)
            make.left.equalTo(scrollV.snp.left).offset(40)
            make.right.equalTo(scrollV.snp.right).offset(-40)
            make.width.equalTo(ScreenWidth - 80)
            make.height.equalTo(46)
        }
        
        scrollV.addSubview(phoneTF)
        phoneTF.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(userTF.snp.bottom).offset(15)
            make.left.equalTo(userTF.snp.left)
            make.right.equalTo(userTF.snp.right)
            make.height.equalTo(46)
        }
        
        pswTF.titleTF.isSecureTextEntry = true
        scrollV.addSubview(pswTF)
        pswTF.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(phoneTF.snp.bottom).offset(15)
            make.left.equalTo(userTF.snp.left)
            make.right.equalTo(userTF.snp.right)
            make.height.equalTo(46)
        }
        
        againPswTF.titleTF.isSecureTextEntry = true
        scrollV.addSubview(againPswTF)
        againPswTF.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(pswTF.snp.bottom).offset(15)
            make.left.equalTo(userTF.snp.left)
            make.right.equalTo(userTF.snp.right)
            make.height.equalTo(46)
        }
        
        imgCodeTF.imgBtn.addTarget(self, action: #selector(imgCodeTapped), for: .touchUpInside)
        scrollV.addSubview(imgCodeTF)
        imgCodeTF.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(againPswTF.snp.bottom).offset(15)
            make.left.equalTo(userTF.snp.left)
            make.right.equalTo(userTF.snp.right)
            make.height.equalTo(46)
        }
        
        codeTF.delegate = self
        scrollV.addSubview(codeTF)
        codeTF.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(imgCodeTF.snp.bottom).offset(15)
            make.left.equalTo(phoneTF.snp.left)
            make.right.equalTo(phoneTF.snp.right)
            make.height.equalTo(46)
        }
        
        netTF.ctl.addTarget(self, action: #selector(netTapped), for: .touchUpInside)
        scrollV.addSubview(netTF)
        netTF.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(codeTF.snp.bottom).offset(15)
            make.left.equalTo(userTF.snp.left)
            make.right.equalTo(userTF.snp.right)
            make.height.equalTo(46)
        }
        
        postTF.ctl.addTarget(self, action: #selector(postTapped), for: .touchUpInside)
        scrollV.addSubview(postTF)
        postTF.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(netTF.snp.bottom).offset(15)
            make.left.equalTo(userTF.snp.left)
            make.right.equalTo(userTF.snp.right)
            make.height.equalTo(46)
        }
        
        confrimBtn.isEnabled = false
        scrollV.addSubview(confrimBtn)
        confrimBtn.snp.makeConstraints { (make) -> Void in
            make.top.equalTo(postTF.snp.bottom).offset(37)
            make.left.equalTo(userTF.snp.left)
            make.right.equalTo(userTF.snp.right)
            make.height.equalTo(50)
            make.bottom.equalToSuperview().offset(-54)
        }
    }
}

extension RegisterView: RDeptTreePopViewDelegate {
    func handleSelected(_ dept: DeptTreeModal?) {
        self.netModal = dept
        self.netTF.titleTF.text = dept?.label
        getFirstViewController()?.popup.dismissPopup()
    }
    
    func handleClose() {
        getFirstViewController()?.popup.dismissPopup()
    }
}

extension RegisterView: BSTextFieldDelegate {
    func handleFetchCode(_ btn: UIButton) {
        var modal = RetrievepwdSendParam()
        modal.username = phoneTF.titleTF.text
        modal.code = imgCodeTF.titleTF.text
        if uuid != nil {
            modal.uuid = uuid
        }
        
        if modal.username == nil || modal.username == "" {
            showToast(witMsg: "请输入手机号")
            return
        }
        
        if modal.code == nil || modal.code == "" {
            showToast(witMsg: "请输入图形验证码")
            return
        }
        
        API.postRetrievepwdSend(withParam: modal) { responseModel in
            if responseModel.errorCode == .Success {
                self.codeTF.start()
            }
        }
    }
}
